<?php

namespace App\Http\Controllers;

use App\Facades\Tx;
use App\Models\Goods;
use App\Models\Message;
use App\Models\Order;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderController extends Controller
{
    public function index(Request $request)
    {
        DB::connection()->enableQueryLog();
        $db = Order::where('uid',\Auth::id());

        if($request->get('status') && $status= $request->get('status'))
        {
            $db = $db->where('status', $status);
        }
        $db = $db->with('goods');
        $list = $db->paginate();
        //dd(DB::getQueryLog());
        return Tx::success($list);
    }

    public function show(Request $request,Order $order)
    {
        if (\Auth::id()==$order->uid || \Auth::id()==$order->sale_id){
            return Tx::success($order);
        }
        return Tx::fail("您没有查看权限");
    }

    public function store(Request $request)
    {
        $this->validate($request,[
            'goods_id' => 'required'
        ]);

        $goods = Goods::where('id',$request->get('goods_id'))->first();

        if($goods->id == \Auth::id()){
            return Tx::fail("无法购买自己的商品");
        }

        if($goods->status != 1)
        {
            return Tx::fail("商品不能下单");
        }

        return Tx::success(Order::create(
            [
                'goods_id' => $goods->id,
                'price' => $goods->price,
                'sale_id' => $goods->uid,
            ]
        ));
    }
    //付款
    public function pay(Request $request,Order $order)
    {

    }
    //确认收货，卖家余额增加
    public function confirmReceive(Request $request,Order $order)
    {
        if($order->status!=3){
            return Tx::fail("卖家暂未发货，无法确认收货");
        }
        $order->update(['status'=>4]);
        User::where('id',$order->sale_id)->increment('money',$order->price);
        Message::create([
                    'uid'=> $order->sale_id,
                    'content'=> "买家已经确认收到您的商品了,订单号：".$order->id
                        ]);
        return Tx::success($order);
    }

    //发货
    public function send(Request $request,Order $order)
    {
        if($order->status!=2){
            return Tx::fail("请等待买家付款");
        }
        $order->update(['status'=>3,'content'=>$request->get("content")]);
        Message::create([
                    'uid'=> $order->uid,
                    'content'=> "卖家已经发货了，赶快去查收吧～"
                ]);
        return Tx::success($order);
    }

    public function waitSend(Request $request){
        $list = Order::where('sale_id',\Auth::id())->where('status',2)->with('goods')->get();
        return Tx::success($list);
    }
}
